package com.ruoyi.data.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.data.domain.LifeCallbackParam;
import com.ruoyi.data.domain.TbData;
import com.ruoyi.data.service.ITbDataService;
import com.ruoyi.data.utils.MD5Utils;
import com.ruoyi.data.utils.OssUtils;
import com.ruoyi.data.utils.QRCodeUtil;
import com.ruoyi.data.utils.SnowFlake;
import com.shumai.utils.HttpUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资料Controller
 * 
 * @author ruoyi
 * @date 2023-04-25
 */
@RestController
@RequestMapping("/data")
public class TbDataController extends BaseController
{
    @Autowired
    private ITbDataService tbDataService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SnowFlake snowFlake;
    private static String appId="gSPhmyV8uvf4ogQ6";
    private static String appSecurity="gSPhmyV8uvf4ogQ6i86esvW0YeGRjORP";
    private static String ngrok_url="http://zsk.free.idcfengye.com";
    /**
     * 查询资料列表
     */
    @RequiresPermissions("data:data:list")
    @GetMapping("/list")
    public TableDataInfo list(TbData tbData)
    {
        startPage();
        List<TbData> list = tbDataService.selectTbDataList(tbData);
        return getDataTable(list);
    }

    /**
     * 导出资料列表
     */
    @RequiresPermissions("data:data:export")
    @Log(title = "资料", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbData tbData)
    {
        List<TbData> list = tbDataService.selectTbDataList(tbData);
        ExcelUtil<TbData> util = new ExcelUtil<TbData>(TbData.class);
        util.exportExcel(response, list, "资料数据");
    }

    /**
     * 获取资料详细信息
     */
    @RequiresPermissions("data:data:query")
    @GetMapping(value = "/{dataId}")
    public AjaxResult getInfo(@PathVariable("dataId") Long dataId)
    {
        return success(tbDataService.selectTbDataByDataId(dataId));
    }

    /**
     * 新增资料
     */
    @RequiresPermissions("data:data:add")
    @Log(title = "资料", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbData tbData)
    {
        tbData.setDataId(snowFlake.getNextId());
        return toAjax(tbDataService.insertTbData(tbData));
    }

    /**
     * 修改资料
     */
    @RequiresPermissions("data:data:edit")
    @Log(title = "资料", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbData tbData)
    {
        return toAjax(tbDataService.updateTbData(tbData));
    }

    /**
     * 删除资料
     */
    @RequiresPermissions("data:data:remove")
    @Log(title = "资料", businessType = BusinessType.DELETE)
	@DeleteMapping("/{dataIds}")
    public AjaxResult remove(@PathVariable Long[] dataIds)
    {
        return toAjax(tbDataService.deleteTbDataByDataIds(dataIds));
    }

    @Autowired
    private OssUtils ossUtils;
    //身份证正面验证
    @RequestMapping("/nationalUpload")
    public Map nationalUpload(MultipartFile file) throws IOException {
        String path = ossUtils.uploadOneFile(file);
        String timestamp = System.currentTimeMillis()+"";
        String sign = DigestUtils.md5Hex(appId + "&" + timestamp + "&" + appSecurity);
        System.err.println("sign: "+sign);
        InputStream inputStream = file.getInputStream();
        byte[] data=new byte[inputStream.available()];
        inputStream.read(data);
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Str = encoder.encode(data);

        String ocrUrl = "https://api.shumaidata.com/v2/idcard/ocr";

        //httpClient   restTemplate
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(ocrUrl);
        ArrayList<NameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("appid",appId));
        list.add(new BasicNameValuePair("timestamp",timestamp));
        list.add(new BasicNameValuePair("sign",sign));
        list.add(new BasicNameValuePair("image",base64Str));

        Map info = null;
        HttpEntity entity = new UrlEncodedFormEntity(list);
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);
        String json = EntityUtils.toString(response.getEntity(), "UTF-8");
        Map map = JSONObject.parseObject(json, Map.class);
        if((Boolean) map.get("success")==true && (Integer)map.get("code")==200){
            Map res = (Map)map.get("data");
            info = (Map)res.get("info");
            info.put("path", path);
            inputStream.close();
            return success(info);
        }else {
            inputStream.close();
            return error("身份证正面验证未通过!");
        }
    }
    //身份证反面验证
    @RequestMapping("/isTheUpload")
    public Map isTheUpload(MultipartFile file) throws IOException {
        String path = ossUtils.uploadOneFile(file);

        String timestamp = System.currentTimeMillis()+"";

        String sign = DigestUtils.md5Hex(appId + "&" + timestamp + "&" + appSecurity);
        System.err.println("sign: "+sign);

        InputStream inputStream = file.getInputStream();
        byte[] data=new byte[inputStream.available()];
        inputStream.read(data);
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Str = encoder.encode(data);

        String ocrUrl = "https://api.shumaidata.com/v2/idcard/ocr";
        //httpClient   restTemplate
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(ocrUrl);
        ArrayList<NameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("appid",appId));
        list.add(new BasicNameValuePair("timestamp",timestamp));
        list.add(new BasicNameValuePair("sign",sign));
        list.add(new BasicNameValuePair("image",base64Str));

        Map info = null;
        HttpEntity entity = new UrlEncodedFormEntity(list);
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);
        String json = EntityUtils.toString(response.getEntity(), "UTF-8");
        Map map = JSONObject.parseObject(json, Map.class);
        if((Boolean) map.get("success")==true && (Integer)map.get("code")==200){
            Map res = (Map)map.get("data");
            info = (Map)res.get("info");
            info.put("path", path);
            inputStream.close();
            return success(info);
        }else {
            inputStream.close();
            return error("身份证反面验证未通过!");
        }
    }

    //ocr营业执照检验
    @PostMapping("/OcrYingYe")
    public Map OcrYingYe(MultipartFile file) throws IOException {
        String path = ossUtils.uploadOneFile(file);
        String timestamp = System.currentTimeMillis() + "";

        //接口地址
        String url = "https://api.shumaidata.com/v2/business_license/ocr";

        //请下载MD5Utils文件,地址为 https://file.tianyandata.cn/demo/utils/MD5Utils.java
        String sign = MD5Utils.encrypt(appId+"&"+timestamp+"&"+appSecurity);
        System.out.println("sign: "+sign);

        InputStream inputStream = file.getInputStream();
        byte[] data=new byte[inputStream.available()];
        inputStream.read(data);
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Str = encoder.encode(data);

        //httpClient   restTemplate
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        ArrayList<NameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("appid",appId));
        list.add(new BasicNameValuePair("timestamp",timestamp));
        list.add(new BasicNameValuePair("sign",sign));
        list.add(new BasicNameValuePair("image",base64Str));

        Map info = null;
        HttpEntity entity = new UrlEncodedFormEntity(list);
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);
        String json = EntityUtils.toString(response.getEntity(), "UTF-8");
        Map map = JSONObject.parseObject(json, Map.class);
        if((Boolean) map.get("success")==true && (Integer)map.get("code")==200){
            Map res = (Map)map.get("data");
            res.put("path", path);
            res.put("code", map.get("code"));
            inputStream.close();
            return success(res);
        }else {
            inputStream.close();
            return error("营业执照验证未通过!");
        }
    }

    @RequestMapping("patternPeople")
    public void patternPeople(String tenantPhone,HttpServletResponse response){
        String timestamp=System.currentTimeMillis()+"";
        String sign = MD5Utils.encrypt(appId+"&"+timestamp+"&"+appSecurity);
        String callbackUrl = ngrok_url+"/tenant/patternPeopleResult";
        System.out.println(callbackUrl);
        //接口地址
        String url = " https://lifeh5.shumaidata.com/index.html#/?"+appId+"&callbackUrl="+callbackUrl+"&complexity=1&timestamp="+timestamp+"&sign="+sign+"&uid="+tenantPhone+"&title=闪付";
        QRCodeUtil.createQRCode(response, url);
    }

    @PostMapping("/patternPeopleResult")
    public void testCallback(@RequestBody LifeCallbackParam param){
        Map map = param.getInfo();
        String uid = param.getUid();
        String cardAndName= (String) redisTemplate.opsForValue().get(uid);
        String[] split = cardAndName.split(",");
        if ((Boolean) map.get("success")==true && (Integer) map.get("code")==200){
            Map data1 = (Map) map.get("data");
            if ((Boolean)data1.get("passed")){
                //获取返回的图片id
                String featureImageId = (String) data1.get("feature_image_id");
                //根据id在网址上获取图片地址
                String fileurl2="https://api.shumaidata.com/v2/life/check/image?imageId="+featureImageId;
                //人证对比
                String peopleCardtimestamp=System.currentTimeMillis()+"";
                String name=split[1];
                String idcard=split[0];
                String image=split[2];
                //人证对比接口地址
                String peopleCardUrl = "https://api.shumaidata.com/v4/face_id_card/compare";
                String peopleCardsign = MD5Utils.encrypt(appId+"&"+peopleCardtimestamp+"&"+appSecurity);
                Map<String,String> peopleCardheaders=new HashMap<>();
                peopleCardheaders.put("Content-Type","application/x-www-form-urlencoded");
                Map<String,Object> peopleCardparams=new HashMap<>();
                peopleCardparams.put("appid", appId);
                peopleCardparams.put("timestamp", peopleCardtimestamp);
                peopleCardparams.put("sign", peopleCardsign);
                peopleCardparams.put("name", name);
                peopleCardparams.put("idcard", idcard);
                peopleCardparams.put("image", image);
                String peopleCardresult= HttpUtils.postForm(peopleCardUrl, peopleCardheaders, peopleCardparams);
                Map peopleCardmap = JSON.parseObject(peopleCardresult, Map.class);
                if ((Boolean) peopleCardmap.get("success")==true && (Integer) peopleCardmap.get("code")==200){
                    Map peopleCardData = (Map) peopleCardmap.get("data");
                    //0.45分以上为同一个人
                    if (peopleCardData.get("msg").equals("系统判断为同一人")){

                    }
                }
            }
        }

    }


}
